import os
import glob
from typing import List

try:
    from cairosvg import svg2png
except ImportError as e:
    raise SystemExit("cairosvg is required. Please install with: pip install cairosvg")

try:
    from PIL import Image
except ImportError:
    raise SystemExit("Pillow is required. Please install with: pip install pillow")


ROOT = os.path.dirname(os.path.abspath(__file__))
SRC_DIR = os.path.join(ROOT, "static", "pic")
TARGET_WIDTH = 1920
TARGET_HEIGHT = 1080


def find_svgs(dir_path: str) -> List[str]:
    return sorted(glob.glob(os.path.join(dir_path, "*.svg")))


def ensure_dirs():
    os.makedirs(SRC_DIR, exist_ok=True)


def svg_to_png_jpg(svg_path: str) -> None:
    base, _ = os.path.splitext(os.path.basename(svg_path))
    png_path = os.path.join(SRC_DIR, f"{base}.png")
    jpg_path = os.path.join(SRC_DIR, f"{base}.jpg")

    with open(svg_path, "rb") as f:
        svg_bytes = f.read()

    # Render to PNG at fixed 16:9 1920x1080 resolution, white background for JPG
    svg2png(bytestring=svg_bytes,
            write_to=png_path,
            output_width=TARGET_WIDTH,
            output_height=TARGET_HEIGHT,
            background_color='white')

    # Convert PNG to high-quality JPEG
    with Image.open(png_path) as im:
        rgb = im.convert("RGB")
        rgb.save(jpg_path, format="JPEG", quality=95, optimize=True, progressive=True)

    print(f"✔ Converted: {os.path.basename(svg_path)} -> {os.path.basename(png_path)}, {os.path.basename(jpg_path)}")


def main():
    ensure_dirs()
    svgs = find_svgs(SRC_DIR)
    if not svgs:
        print(f"No SVG files found in: {SRC_DIR}")
        return

    print(f"Found {len(svgs)} svg(s). Converting to 1920x1080 PNG and JPG...")
    for svg in svgs:
        try:
            svg_to_png_jpg(svg)
        except Exception as e:
            print(f"[ERROR] Failed to convert {svg}: {e}")

    print("All done. Files saved to static\\pic\\ as .png and .jpg.")


if __name__ == "__main__":
    main()